<template>
  <div class="agent" v-loading="loading">
    <div v-show = "agentName">
      <div class="top">
        <div class="search">
          <div class="contition">
            <div class="wrap_time">
              <date-time type="other_half_hour" @changeType="changeType" @changeDateS="childTimeChange" :query="query" @isFold="isShowFold" :isTimePeriod = "true" :isOther="true"></date-time>
              <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
              <div class="clear"></div></div>
            <div class="wrap_drop">
              <unfold :isShow="isFold" :title="[]">
                <template slot="unfoldSlot">
                  <div class="agent_search">
                    <div class="skill">
                      <el-radio-group v-model="radio1"
                                    size = "mini"
                                    @change = "changeAgentBig">
                        <el-radio :label="1">{{$t('report.lookAgentWork')}}</el-radio>
                        <el-radio :label="0">{{$t('report.lookSkillWork')}}</el-radio>
                        <span class="tip">
                          <el-tooltip
                            transition="fade-leave"
                            effect="dark"
                            :content="$t('report.queueChangeAgentTip')"
                            placement="bottom">
                            <i class="icon iconfont icon-tixingweizhi"></i>
                          </el-tooltip>
                        </span>
                      </el-radio-group></div>
                    <div class="wrap_conti" v-show="radio1">
                      <span class="chan_ag">{{$t('report.chooseAgent')}}:</span>
                      <el-radio-group v-model="radio3"
                                    size = "mini"
                                    @change = "changeAgent">
                        <div>
                          <el-radio :label="1">{{$t('public.checkAll')}}</el-radio></div>
                        <div class="skill">
                          <el-radio :label="2">{{$t('report.accordAgentChoose')}}</el-radio>
                          <!-- <el-select v-model="query.selectedAgentList"
                                       multiple
                                       filterable
                                       :disabled = "radio3 !== 2"
                                       size="mini"
                                       @change="agentsChange"
                                       :placeholder="$t('report.pleChoseAgent')">
                              <el-option
                                v-for="item in selectAgents"
                                :label="item.label"
                                :value="item.value"
                                :key="item.value">
                              </el-option>
                            </el-select> -->
                          <m7Select class="el-select" :disabled = "radio3 !== 2" filterable multiple :options="selectAgents" v-model="query.selectedAgentList"></m7Select>
                          <el-checkbox :disabled = "radio3 !== 2"
                                       v-model.trim="query.includeSubordinate">
                            {{$t('public.includeSubordinate')}}</el-checkbox></div>
                        <div class="skill">
                          <el-radio :label="3">{{$t('report.chooseSkillAgent')}}</el-radio>
                          <el-select size="mini"
                                     v-model.trim="currentQueue"
                                     :placeholder="$t('report.queueNaSea')"
                                     multiple
                                     :disabled = "radio3 !== 3"
                                     filterable
                                     @change = "change">
                            <el-option v-for="item in queues"
                                       :label="item.DisplayName"
                                       :value="item._id"
                                       :key="item._id"></el-option>
                          </el-select>
                          <el-checkbox :disabled = "radio3 !== 3"
                                         v-model.trim="isShowAgent">
                              {{$t('report.isShowSkillAgent')}}</el-checkbox></div>
                        <div class="skill dept">
                          <el-radio :label="4">{{$t('report.accordDeptChoose')}} </el-radio>
                          <el-select size="mini"
                                     v-model.trim="currentdept"
                                     :placeholder="$t('report.deptNaSea')"
                                     multiple
                                     :disabled = "radio3 !== 4"
                                     filterable
                                     @change = "changeDept">
                            <el-option v-for="item in depts"
                                       :label="item.name"
                                       :value="item.treePath"
                                       :key="item._id"></el-option>
                          </el-select>
                          <el-checkbox :disabled = "radio3 !== 4"
                                       v-model.trim="isShowDeptAgent"
                                       @change = changeShowDept>
                              {{$t('report.isShowDeptAgent')}}</el-checkbox></div>
                      </el-radio-group>
                    </div>
                    <div class="wrap_conti" v-show="!radio1">
                      <div class="skill">
                        <span class="ski">{{$t('report.chooseSkill')}}:</span>
                        <el-select size="mini"
                                   v-model.trim="currentQueueS"
                                   :placeholder="$t('report.queueNaSea')"
                                   filterable
                                   multiple
                                   @change = "changeSkill">
                          <el-option v-for="item in queues"
                                     :label="item.DisplayName"
                                     :value="item.Exten"
                                     :key="item._id"></el-option>
                        </el-select>
                      </div>
                    </div>
                  </div>
                </template>
              </unfold>
            </div>
          </div>
        </div>
        <affix :label="$t('report.agentWorkLoRe')"></affix>
      </div>
      <div :id="id">
        <el-row class="ichars">
          <highcharts :options="options24out"></highcharts>
          <div class="notes">
            <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
            <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
          </div>
        </el-row>
        <div class="tab agent_table">
          <div class="export">
            <el-button class="primary_btn fr formal" v-if="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
            <el-button class="primary_btn fr set_header" v-on:click.stop="getConfigData" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

            <!-- <el-button class="primary_btn fr report_excel_btn"
              v-if="$store.getters.exportFromEnd"
              v-on:click.stop="exportExcel"
            >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->
            <el-button class="primary_btn fr report_excel_btn"
              v-on:click.stop="exportXlsx"
            >{{$t('report.exportXls')}}</el-button>
            <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
            <el-tooltip class="item" :content="$t('report.detailText')" effect="dark" placement="bottom">
              <el-button class="primary_btn fr pdf" v-show="isShowDetailExport" v-on:click.stop="exportExcel(true)">{{$t('report.exportDetailXls')}}
                <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
              </el-button>
            </el-tooltip>
            <el-select @change="changeLookData" size="mini" class="fr pdf" v-model="data_type">
              <el-option value="hasData" :label="$t('report.lookHasData')"></el-option>
              <el-option value="allData" :label="$t('report.lookHasAllData')"></el-option>
            </el-select>
          </div>
          <div class="deploy">
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title">
                  <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
                </template>
                <div>
                  {{$t('report.callOutNum')}}<br>
                  {{$t('report.callOutSucNum')}}<br>
                  {{$t('report.callInRingNum')}}<br>
                  {{$t('report.callInConnectNum')}}<br>
                  {{$t('report.callInConnectRate')}}<br>
                  {{$t('report.callInTurnNum')}}<br>
                  <!-- {{$t('report.callOnlineAllTime')}}<br> -->
                  {{$t('report.callInAllTime')}}<br>
                  {{$t('report.callInAverTime')}}<br>
                  {{$t('report.callOutTotalTime')}}<br>
                  {{$t('report.callOutAverTi')}}<br>
                  {{$t('report.callOutAverHoursNum')}}<br>
                  {{$t('report.employeeRate')}}<br>
                  {{$t('report.callBusyTime')}}<br>
                  {{$t('report.callRestAllTime')}}<br>
                  {{$t('report.callCustomStatusTime')}}<br>
                  {{$t('report.systemBusy')}}<br>
                  {{$t('report.RingingTimeLength')}}<br>
                  {{$t('report.HoldTimeLength')}}<br>
                  {{$t('report.ConsultTimeLength')}}<br>
                  {{$t('report.ThreeWayCallTimeLength')}}<br>
                  21.{{$t('report.callTalkTime')}}<br>
                  22.{{$t('report.callOnlineAllTime')}}<br>
                  23.{{$t('report.UnansweredCalls')}}<br>
                  24.{{$t('report.IntegratedCallRate')}}<br>
                  25.{{$t('report.TransferCount')}}<br>
                  26.{{$t('report.TransferAcceptRate')}}<br>
                  27.{{$t('report.NormalTransferTimeLength')}}<br>
                  28.{{$t('report.DialTransferTimeLength')}}<br>
                  29.{{$t('report.TransferTimeLength')}}<br>
                  30.{{$t('report.IncomingRingingTimeLength')}}<br>
                  31.{{$t('report.OutgoingWaitingTimeLength')}}<br>
                  32.{{$t('report.MaxCallTimeLength')}}<br>
                  33.{{$t('report.HoldSoftphoneTimeLength')}}<br>
                  34.{{$t('report.HoldSoftphoneCount')}}<br>
                  35.{{$t('report.OutgoingAbandonCount')}}<br>
                  36.{{$t('report.RollOutCount')}}<br>
                  37.{{$t('report.RepeatCallInBy24hCount')}}<br>
                  38.{{$t('report.RepeatCallInBy48hCount')}}<br>
                  39.{{$t('report.firstSolutionNumber24h')}}<br>
                  40.{{$t('report.firstSolutionNumber48h')}}<br>
                  41.{{$t('report.firstCallsReceivedNumber24h')}}<br>
                  42.{{$t('report.firstCallsReceivedNumber48h')}}<br>
                  43.{{$t('report.RedirectAgentDeal')}}<br>
                  44.{{$t('report.RedirectAgentNotDeal')}}<br>
                  45.{{$t('report.RedirectGroupDeal')}}<br>
                  46.{{$t('report.RedirectGroupNotDeal')}}<br>
                  47.{{$t('report.onlineStatusTotalDays')}}<br>
                  48.{{$t('report.customerHandUpSpeed')}}<br>
                  49.{{$t('report.calloutAutobusytime')}}<br>
                  50.{{$t('report.callinAutobusytime')}}<br>
                  51.{{$t('report.pickPpCount20s')}}<br>
                  52.{{$t('report.forwardedCallsReceivedIn20s')}}<br>
                  <!-- 30.{{$t('report.FirstHangupCount')}} -->
                  <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                  <p v-for="(item, index) in formulas" :key="item.name">
                    {{index + 53}}.{{item.formulaInstr}}
                  </p>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <checkbox-table :isRemark="true" :data="serveNumData" @agentName = "searchName" :sum="sum" :config="[...Config, ...formulasConfig]" @tellme = "reducteDate"> </checkbox-table>
        </div>
      </div>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
        <span>{{$t('report.reportExportTipTitle')}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
          <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
        </span>
      </el-dialog>
      <header-option :isDisableHeader="isDisableHeader" :isdisable="isdisable" v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_agent" v-on:close="close" :headCustom="formulasConfig"></header-option>
    </div>
    <queryAgentTime v-show="!agentName" ref="myChild" @flag = "show" :customConfig="formulasConfig" :formulas="formulas"  :cityName = "{queryOne, AgentID, name, dateSource}"></queryAgentTime>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :isRemark="true" :headOptionsConfig="Config" @closeFormulaDialog="closeFormulaDialog" reportName="通话座席工作量报表" :reportType="id"/>
  </div>
</template>
<script>
  import dateTime from '../base/dateDrill.vue' // 时间插件
  import unfold from '../../../ui-modules/unfold/index.vue' // 折叠插件
  import affix from '../../../ui-modules/affix/Affix.vue'
  import {exportReportPdf, checkTime, searchTime, colorConfigArr, mixData, sortDataByKey, headOptionsToXlsxHeaders} from '@/utils/reportUtils.js'
  import {deepClone, getCallTimeLength, optionTimeTypeCheck, getDateTime, isHasFunc} from '@/utils/m7Utils.js'
  import checkboxTable from '../base/checkboxTable.vue'
  import headerOption from '../base/headerOption.vue'
  import queryAgentTime from './QueryAgentTime.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  // import { parseFormulaStr, dal2Rpn, STATUS, evalRpn, toNumber } from '../base/formulaUtil.js'

  export default {
    name: 'callReportAgent',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        data_type: 'hasData', // 查看数据类型
        dateType: 'day',
        // wrapAgents: false, // 是防止座席数据量展示太大设置样式index -1
        isShowAgent: false, // 是否展示技能组下的座席
        isShowDeptAgent: false, // 是否展示部门下的座席
        isFold: false,  // 是否展示搜索条件
        currentQueueS: [], // 技能组号
        radio3: 1, // 各座席工作量下面选择切换绑定得值
        radio1: 1, // 各座席工作量和各技能组切换绑定值
        depts: [], // 部门渲染下拉数据
        currentdept: [], // 选择部门绑定得id值
        // ArrayList: [],
        dateSource: {}, // 像子组件传时间选择值
        cloneQuery: {}, // clone查询条件 初次查询用
        loading: false, // 查询数据遮罩开关
        tableDate: [], // 查询出来未经处理得数据
        name: '', // 传给子组件座席名字
        queryOne: {}, // 传给子组件条件
        AgentID: '', // 传给子组件座席id
        agentName: true, // 是否显示子组件开关
        queues: [], // 技能组渲染数据
        currentQueue: [], // 各座席量技能组绑定值
        selectedAgentListClone: [], // 是否展示座席得复制版
        query: {
          selectedAgentList: [], // 座席id集合
          includeSubordinate: false // 是否显示当前座席下级开关
          // hiddenCurrentAgent: false
        },
        isShow: false, // 配置表头弹层开关
        dialogVisible: false, // 导出pdf开关
        headOptions: {},
        headOptionsShow: {}, // 配置表头
        agents: [], // 渲染座席数据
        id: 'call_report_agent',
        serveNumData: [], // 表格数据
        sum: [], // 合计
        isDisableHeader: ['CallOutAccessCount', 'CallOutAcceptCount', 'LOGIN_TIME_LENGTH', 'CallOutTimeLength', 'CallOutAverageTimeLength', 'AverageHourCallCount', 'AgentUtilization', 'ShowPhoneBarStatus', 'IDLE_TIME_LENGTH'], // 按技能组查询隐藏得表头字段
        isdisable: false,
        series4high: {}, // 图表数据
        options24out: { // icharts图表配置
          chart: {
            type: 'column',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            categories: []
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: {
              text: ''
            }
          },
          title: {
            text: this.$t('report.callAgentJob')
          },
          legend: {
            align: 'center',
            verticalAlign: 'top',
            x: 0,
            y: 20
          },
          tooltip: {
            formatter: function () {
              var s = '<span style="font-size:10px">' + this.x + '</span><table>'
              let self = this
              self.points.forEach(function (item) {
                var unit = ''
                if (item.series.name.slice(-2) === '时长') {
                  unit = 's'
                } else if (item.series.name.slice(-1) === '率') {
                  unit = '%'
                }
                s += '<tr><td style="color:' + item.series.color + ';padding:0">' + item.series.name + ': </td><td style="padding:0"><b>' + item.y + '' + unit + '</b></td></tr>'
              })
              s += '</table>'
              return s
            },
            shared: true,
            useHTML: true
          },
          plotOptions: {
          },
          credits: {enabled: false},
          series: []
        },
        isSearch: false,
        formulas: [] // 公式数据
      }
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.tableDate || this.tableDate.length === 0) {
          return
        }
        this.tableDate = mixData(deepClone(this.tableDate), this.formulas)
        this.dealDate(deepClone(this.tableDate))
      },
      // 选择后是否显示当前下座席
      isShowAgent (cur) {
        if (cur) {
          this.query.selectedAgentList = this.selectedAgentListClone
        } else {
          this.query.selectedAgentList = []
        }
      }
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return this.agents
      },
      // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['week', 'month', 'other_half_hour']
        return type.includes(this.dateType)
      },
      // 是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      // 计算表头
      Config () {
        return this.getConfig(this.headOptions)
      },
      // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type,
            remark: d.remark,
            remarkVal1: d.remarkVal1,
            remarkVal2: d.remarkVal2,
            symbol: d.symbol
          }
        })
      }
    },
    methods: {
      // 切换数据查看方式
      changeLookData () {
        this.search()
      },
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      // 导出详情为自定义进行得判断
      thanThirty (query) {
        let normalStartTime = query.normalStartTime
        let normalEndTime = query.normalEndTime
        let endTIme = normalEndTime.getTime()
        let startTime = normalStartTime.getTime()
        let diff = (endTIme - startTime) / (1000 * 60 * 60 * 24)
        // 大于三十天更改自定义得开始时间
        if (diff > 31) {
          let time = new Date(endTIme - 1000 * 60 * 60 * 24 * 31)
          let newStartTime = getDateTime(time, 'date')
          let lastTime = query.EndTime.split(' ')[1]
          query.StartTime = `${newStartTime} ${lastTime}`
        }
      },
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 座席组件改变得事件
      // agentsChange () {
      //   if (this.wrapAgents) {
      //     this.wrapAgents = false
      //   }
      // },
      // 是否展示部门下的座席
      changeShowDept (cur) {
        if (cur) {
          this.query.selectedAgentList = this.selectedAgentListClone
        } else {
          this.query.selectedAgentList = []
        }
      },
      // 钻入需要渲染的原始时间数据, 时间子组件传过来的方法
      childTimeChange (obj) {
        this.dateSource = obj
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 各座席工作量和技能组切换, 初始化一些数据
      changeAgentBig (num) {
        delete this.query.queryExten
        this.currentQueueS = []
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentdept = []
        this.currentQueue = []
        this.query.includeSubordinate = false
        this.isShowAgent = false
        this.isShowDeptAgent = false
      },
      // 切换技能组
      changeSkill (id) {
        this.query.queryExten = id.join(',')
      },
      // 子组件传上来的方法 判断是否展示当前列得数据和合计 hcharts展示
      reducteDate (date, num) {
        let noDealDate = []
        for (let i = 0; i < date.length; i++) {
          for (let j = 0; j < this.tableDate.length; j++) {
            if (date[i].AgentID === this.tableDate[j].AgentID) {
              noDealDate.push(this.tableDate[j])
              break
            }
          }
        }
        this.dealDate(noDealDate, num)
      },
      // 各座席量选择切换
      changeAgent () {
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentdept = []
        this.currentQueue = []
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.query.includeSubordinate = false
      },
      // 部门切换执行方法，筛选座席
      changeDept (deptTreePaths) {
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        let deptIds = [] // 创建部门id数组集
        if (deptTreePaths.length !== 0) {
          for (let i = 0; i < deptTreePaths.length; i++) {
            if (deptTreePaths[i] === 'noDept') {
              deptIds.push('')
            } else {
              let deptIdArr = deptTreePaths[i].split('/')
              let deptId = deptIdArr[deptIdArr.length - 2] // 当前部门id
              deptIds.push(deptId) // 像部门数组中添加当前部门id
              for (let j = 0; j < this.depts.length; j++) {
                let isDeptIdArr = this.depts[j].treePath.split(deptId + '/')[1] // 判断当前部门下面得部门是否存在
                if (isDeptIdArr) {
                  deptIds = deptIds.concat(isDeptIdArr.split('/').filter(item => item))
                }
              }
            }
          }
          deptIds = Array.from(new Set(deptIds)) // 部门id去重
          let cloneAgentsArr = []
          cloneAgentsArr = this.agents.filter(item => { // 过滤座席信息得部门是否在部门数组里，是则返回
            return deptIds.includes(item.deptId)
          })
          cloneAgentsArr.map(item => {
            this.selectedAgentListClone.push(item.value)
          })
          if (this.isShowDeptAgent) {
            this.query.selectedAgentList = this.selectedAgentListClone
          }
        }
      },
      // 各座席量下的技能组切换筛选座席
      change (peerIds) {
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        if (peerIds.length === 0) {
          return
        }
        let agentIds = []
        peerIds.map((id) => {
          this.queues.map((item) => {
            if (item._id === id) {
              agentIds = agentIds.concat(item.AssignMembers)
            }
          })
        })
        agentIds.map((obj) => {
          if (obj) {
            this.selectedAgentListClone.push(obj.agentID)
          }
        })
        if (this.isShowAgent) {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
          this.query.selectedAgentList = this.selectedAgentListClone
        } else {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
        }
      },
      // 子组件传上来的方法，判断是否显示子组件
      show () {
        this.agentName = true
      },
      // 初始化子组件的查询条件  点击座席
      searchName (id, name) {
        console.log(id,name,'11111111111')
        this.queryOne.AgentID = id
        this.name = name
        this.AgentID = id
        let myQuery = deepClone(this.query)
        // 转化timeType查询条件
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.selectedAgentList = myQuery.selectedAgentList.join(',')
        myQuery.reportType = 'call_report_agent'
        myQuery.AgentID = ''
        this.queryOne = deepClone(myQuery)
        this.agentName = false
        this.$nextTick(() => {
          this.$refs.myChild.search1()
        })
      },
      // 判断是否需要请求自定义软电话条状态字段
      getConfig (headOptions, isPromise) {
        if (!headOptions.Config || headOptions.Config.length === 0) {
          return []
        }
        // 判断是否显示自定义字段下面的字段
        let phonebarEnable = ''
        let headerConfig = []
        headerConfig = deepClone(headOptions.Config)
        for (let i = 0; i < headerConfig.length; i++) {
          if (headerConfig[i].name === 'ShowPhoneBarStatus' && headerConfig[i].show === true) {
            phonebarEnable = true
            headerConfig = headerConfig.slice(0, i).concat(headerConfig.slice(i + 1, headerConfig.length))
          }
        }
        var promise = null
        if (phonebarEnable === true) {
          let dataCti = {
            PBX: this.$store.state.session.user.pbx,
            Account: this.$store.state.session.user.account,
            IsEnable: '1'
          }
          // 请求自定义软电话的几个字段
          promise = this.$store.dispatch('queryAgentReportCti', dataCti).then((res) => {
            let phonebarRes = deepClone(res)
            let systemBarStatusArr = ['0', '1', '2', '99']
            if (phonebarRes.success) {
              for (let m = 0; m < phonebarRes.list.length; m++) {
                if (!systemBarStatusArr.includes(phonebarRes.list[m].PhoneBarItemId)) {
                  // if (phonebarRes.list[m].PhoneBarItemName === '忙碌') {
                  //   let phoneConfig = {
                  //     name: 'BUSY_TIME_LENGTH',
                  //     displayname: phonebarRes.list[m].PhoneBarItemName + this.$t('report.totalTimeLength'),
                  //     show: true,
                  //     order: 50 + m
                  //   }
                  //   headerConfig.push(phoneConfig)
                  // } else {
                  let phoneConfig = {
                    name: 'STATE' + phonebarRes.list[m].PhoneBarItemId + '_TIME_LENGTH',
                    displayname: phonebarRes.list[m].PhoneBarItemName + this.$t('report.totalTimeLength'),
                    show: true,
                    order: 50 + m
                  }
                  headerConfig.push(phoneConfig)
                  // }
                }
              }
              headOptions.Config = deepClone(headerConfig)
              return headerConfig
            }
          })
        }
        if (isPromise) {
          return promise || Promise.resolve(headerConfig)
        }
        return headerConfig
      },
      // 抽出查询条件
      getSearchQueryData () {
        let data = {reportType: 'call_report_agent'}
        let userCondition = {type: this.$store.state.session.user.type, moduleUsers: this.$store.state.session.user.moduleUsers}
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = null;
          if (this.dateType === 'week') { // 周报允许到天
            myQuery.timeType = 'other'
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.selectedAgentList = this.query.selectedAgentList.join(',')
        myQuery.reportType = 'call_report_agent'
        myQuery.account = this.$store.state.session.user.account
        myQuery.user = userCondition
        myQuery.AgentID = ''
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          myQuery.selectedAgentList = '000000'
        } else if (this.selectedAgentListClone.length !== 0) {
          myQuery.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        //  图表标题 加入 定时段的 时间
        let highchartsTitle = ''
        if (myQuery.timePeriod) {
          let timePeriodStartStr = myQuery.timePeriodStart || '00:00'
          let timePeriodEndStr = myQuery.timePeriodEnd || '23:59'
          highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
        }
        this.options24out.title.text = this.$t('report.callAgentJob') + highchartsTitle
        delete myQuery.normalEndTime
        delete myQuery.normalStartTime
        data = myQuery
        if (data.TimeType === 'other_half_hour') {
          delete data.yearReport
          delete data.monthReport
          delete data.dayReport
        }
        if (this.data_type === 'allData') {
          data.completion = 'yes'
        }
        return data
      },
      // 查询数据的方法
      search () {
        var data = this.getSearchQueryData()

        if (!data) {
          return
        }

        var myQuery = data.query || deepClone(this.query)
        console.log(data,'data')

        this.cloneQuery = myQuery
        this.loading = true
        this.$store.dispatch('queryCallAgentReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.isSearch = true
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
            if (resp.success) {
              this.formulas = resp.data.Formulas
              this.tableHeader = optionTimeTypeCheck(res.tableHeader)
              this.tableDate = deepClone(mixData(res.data, this.formulas))
              this.dealDate(deepClone(this.tableDate), myQuery)
              this.loading = false
            }
          })
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var data = this.getSearchQueryData()

        if (!data) {
          return
        }

        var myQuery = data.query || deepClone(this.query)

        this.cloneQuery = myQuery
        this.loading = true
        this.$store.dispatch('queryCallAgentReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var headOptions = optionTimeTypeCheck(res.tableHeader)
          var resData = deepClone(mixData(res.data, this.formulas))
          this.getConfig(headOptions, true).then(Config => {
            var sum = []
            if (resData.length !== 0) {
              sum = this.getSum(resData, headOptions, myQuery, true)
            }
            var ConfigsTemp = []
            Config.forEach(config => {
              ConfigsTemp.push(config)
              if (config.name === 'agent_name') {
                ConfigsTemp.push({
                  show: config.show,
                  displayname: '工号',
                  name: 'agent_exten'
                })
              }
            })
            Config = ConfigsTemp
            // resData = sortDataByKey(resData, 'agent_name')
            var tableData = resData.concat(sum)
            var headers = headOptionsToXlsxHeaders([...Config, ...this.formulasConfig])

            var dh = XlsxUtil.getDownloadHelper(headers, tableData)
            var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
            dh.download(this.$t('report.callReportAgent') + timeStamp)
          })
        })
      },
      // 计算合计
      getSum (resData, headOptions, myQuery, isExport) {
        if (resData.length === 0) {
          return [{}]
        }
        let sum = [{agent_name: this.$t('report.total')}]
        let agentInfo = this.$store.getters.agents
        let headConfig = [...headOptions.Config, ...this.formulasConfig]
        let maxLen = 0 // 判读最大通话时长
        for (let i = 0; i < resData.length; i++) {
          let item = resData[i]
          let getAgent = agentInfo[item.AgentID]
          if (!isExport) {
            let agentXAxis = ''
            agentXAxis = getAgent ? getAgent.displayName + '(' + getAgent.exten + ')' : ''
            this.options24out.xAxis.categories.push(agentXAxis)
          }
          for (let j in item) {
            if (!isExport) {
              // 渲染charts
              if (this.series4high[j] === undefined) {
                this.series4high[j] = []
              }
              if (['LOGIN_TIME_LENGTH', 'CallInAverageTimeLength', 'CallInTimeLength', 'CallOutAverageTimeLength', 'CallOutTimeLength'].indexOf(j) >= 0) {
                this.series4high[j].push(item[j])
              } else {
                delete this.series4high[j]
              }
            }
            if (sum[0][j] === undefined) {
              sum[0][j] = 0
            }
            if (j !== 'agent_name') {
              if (j === 'MaxCallTimeLength') {
                if (item[j] > maxLen) {
                  maxLen = item[j]
                  sum[0][j] = maxLen
                } else {
                  sum[0][j] = maxLen
                }
              } else {
                sum[0][j] += item[j]
              }
            }
          }
          item.agent_name = getAgent ? getAgent.displayName + '(' + getAgent.exten + ')' : ''

          if (isExport) {
            item.agent_name = getAgent ? getAgent.displayName : ''
            item.agent_exten = getAgent ? getAgent.exten : ''
          }
          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getCallTimeLength(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            }
          })
          // item.BUSY_TIME_LENGTH = getCallTimeLength(item.BUSY_TIME_LENGTH)
          // item.STATE99_TIME_LENGTH = getCallTimeLength(item.STATE99_TIME_LENGTH)
          item.STATE3_TIME_LENGTH = getCallTimeLength(item.STATE3_TIME_LENGTH)
          // item.STATE2_TIME_LENGTH = getCallTimeLength(item.STATE2_TIME_LENGTH)
          item.STATE4_TIME_LENGTH = getCallTimeLength(item.STATE4_TIME_LENGTH)
          item.STATE5_TIME_LENGTH = getCallTimeLength(item.STATE5_TIME_LENGTH)
          item.STATE6_TIME_LENGTH = getCallTimeLength(item.STATE6_TIME_LENGTH)
          item.STATE7_TIME_LENGTH = getCallTimeLength(item.STATE7_TIME_LENGTH)
          item.STATE8_TIME_LENGTH = getCallTimeLength(item.STATE8_TIME_LENGTH)
          item.STATE9_TIME_LENGTH = getCallTimeLength(item.STATE9_TIME_LENGTH)
        }
        resData = sortDataByKey(resData, 'agent_name', 'string')
        // 计算合计
        let Dividend = sum[0].CallInAccessCount
        let Divisor = sum[0].CallInAcceptCount
        if (Dividend > 0 && Divisor >= 0) {
          sum[0].CallInAcceptRate = Math.round((sum[0].CallInAcceptCount / Dividend) * 100)
        } else if (Dividend === 0 || Divisor === 0) {
          sum[0].CallInAcceptRate = '0'
        } else {
          sum[0].CallInAcceptRate = ''
        }
        if (sum[0].LOGIN_TIME_LENGTH === 0 || (sum[0].CallInAcceptCount + sum[0].CallOutAcceptCount) === 0) {
          sum[0].AgentUtilization = '0'
        } else {
          var molecular = sum[0].CallInTimeLength + sum[0].CallOutTimeLength
          if (sum[0].STATE99_TIME_LENGTH) {
            molecular = molecular + sum[0].STATE99_TIME_LENGTH
          }
          var denominator = sum[0].LOGIN_TIME_LENGTH
          for (var k = 2; k < 10; k++) {
            if (sum[0]['STATE' + k + '_TIME_LENGTH']) {
              denominator = denominator - sum[0]['STATE' + k + '_TIME_LENGTH']
            }
          }
          sum[0].AgentUtilization = Math.round(molecular / denominator * 100)
          sum[0].AgentUtilization = sum[0].AgentUtilization < 0 ? '0' : sum[0].AgentUtilization
        }
        if (sum[0].CallInAcceptRate === '') {
          sum[0].AgentUtilization = ''
        }
        // 特殊处理的table合计
        for (var i = 0; i < headConfig.length; i++) {
          if (headConfig[i].name === 'AverageHourCallCount') {
            if (sum[0].LOGIN_TIME_LENGTH === 0) {
              sum[0][headConfig[i].name] = 0
            } else if (sum[0].LOGIN_TIME_LENGTH <= 1800) {
              sum[0][headConfig[i].name] = sum[0].CallInAcceptCount + sum[0].CallOutAcceptCount + sum[0].TransferAcceptCount
            } else {
              sum[0][headConfig[i].name] = Math.round((sum[0].CallInAcceptCount + sum[0].CallOutAcceptCount + sum[0].TransferAcceptCount) * 1800 / sum[0].LOGIN_TIME_LENGTH)
            }
          } else if (headConfig[i].name === 'CallInAverageTimeLength') {
            if ((sum[0].CallInAcceptCount + sum[0].TransferAcceptCount) === 0) {
              sum[0][headConfig[i].name] = 0
            } else {
              // 呼入通话平均时长还原
              sum[0][headConfig[i].name] = Math.round(sum[0].CallInTimeLength / (sum[0].CallInAcceptCount + sum[0].TransferAcceptCount))
            }
          } else if (headConfig[i].name === 'CallOutAverageTimeLength') {
            if (sum[0].CallOutAcceptCount === 0) {
              sum[0][headConfig[i].name] = 0
            } else {
              sum[0][headConfig[i].name] = Math.round(sum[0].CallOutTimeLength / sum[0].CallOutAcceptCount)
            }
          } else if (headConfig[i].name === 'IntegratedCallInAcceptRate') {
            // 呼入接通率
            let callInNum = sum[0].CallInAccessCount + sum[0].TransferUnacceptCount + sum[0].TransferAcceptCount
            if (callInNum === 0) {
              sum[0][headConfig[i].name] = '0%'
            } else {
              sum[0][headConfig[i].name] = Math.round((sum[0].CallInAcceptCount + sum[0].TransferAcceptCount) / callInNum * 100) + '%'
            }
          } else if (headConfig[i].name === 'TransferAcceptRate') {
            // 转接电话接通率
            if (sum[0].TransferCount === 0) {
              sum[0][headConfig[i].name] = '0%'
            } else {
              sum[0][headConfig[i].name] = Math.round(sum[0].TransferAcceptCount / sum[0].TransferCount * 100) + '%'
            }
          }
        }
        sum = mixData(sum, this.formulas)
        headConfig.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            sum[0][option.name] = getCallTimeLength(sum[0][option.name])
          } else if (option.timeType && option.timeType === 'second') {
            sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
          } else if (option.timeType && option.timeType === 'percent') {
            sum[0][option.name] = sum[0][option.name] + '%'
          }
        })

        // sum[0].BUSY_TIME_LENGTH = getCallTimeLength(sum[0].BUSY_TIME_LENGTH)
        // sum[0].STATE99_TIME_LENGTH = getCallTimeLength(sum[0].STATE99_TIME_LENGTH)
        sum[0].STATE3_TIME_LENGTH = getCallTimeLength(sum[0].STATE3_TIME_LENGTH)
        // sum[0].STATE2_TIME_LENGTH = getCallTimeLength(sum[0].STATE2_TIME_LENGTH)
        sum[0].STATE4_TIME_LENGTH = getCallTimeLength(sum[0].STATE4_TIME_LENGTH)
        sum[0].STATE5_TIME_LENGTH = getCallTimeLength(sum[0].STATE5_TIME_LENGTH)
        sum[0].STATE6_TIME_LENGTH = getCallTimeLength(sum[0].STATE6_TIME_LENGTH)
        sum[0].STATE7_TIME_LENGTH = getCallTimeLength(sum[0].STATE7_TIME_LENGTH)
        sum[0].STATE8_TIME_LENGTH = getCallTimeLength(sum[0].STATE8_TIME_LENGTH)
        sum[0].STATE9_TIME_LENGTH = getCallTimeLength(sum[0].STATE9_TIME_LENGTH)
        if (sum[0].CallInAcceptRate === '') {
          sum[0].LOGIN_TIME_LENGTH = ''
          sum[0].CallInTimeLength = ''
          sum[0].CallInAverageTimeLength = ''
          sum[0].CallOutTimeLength = ''
          sum[0].CallOutAverageTimeLength = ''
        }

        if (resData.length !== 0) {
          sum[0].agent_name = this.$t('report.total')
        }
        return sum
      },
      // 处理数据渲染table和图表
      dealDate (data, condition) {
        let myQuery = condition
        if (condition !== 1) {
          this.headOptions = deepClone(this.tableHeader)
        }
        let resData = deepClone(data)
        this.options24out.xAxis.categories = []
        this.series4high = {}
        this.sum = this.getSum(resData, this.headOptions, myQuery)
        if (condition !== 1) {
          this.serveNumData = resData
        }
        // 渲染icharts图表
        this.options24out.series = []
        for (let i in this.headOptions.Config) {
          let item = this.headOptions.Config[i]
          if (['LOGIN_TIME_LENGTH', 'CallInAverageTimeLength', 'CallInTimeLength', 'CallOutAverageTimeLength', 'CallOutTimeLength'].indexOf(item.name) >= 0) {
            this.options24out.series.push({
              name: item.displayname,
              data: this.series4high[item.name]
            })
          }
        }
        if (resData.length !== 0) {
          this.sum[0].agent_name = this.$t('report.total')
        } else {
          this.sum = [{agent_name: this.$t('report.total')}]
        }
      },
      // 获取表头数据
      getConfigData () {
        this.$store.dispatch('getReportTableHeader', 'call_report_agent').then((res) => {
          if (this.query.queryExten) {
            this.isdisable = true
          } else {
            this.isdisable = false
          }
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 导出表格数据执行的方法(后端)
      exportExcel (isDetailExpot) {
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour'&& isDetailExpot && this.dateType == 'week') {
          myQuery.timeType = 'other'
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 是否为自定义时间导出并且点击详细导出
        if (myQuery.timeType === 'other_half_hour' && isDetailExpot && this.dateType !== 'week') {
          this.thanThirty(myQuery)
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'agentExport'
        myQuery.userType = this.$store.state.session.user.type
        myQuery.dataDB = this.$store.state.session.account.dataDB
        myQuery.selectedAgentList = this.query.selectedAgentList.join(',')
        myQuery.user = this.$store.state.session.user._id
        myQuery.reportType = 'call_report_agent'
        myQuery.pbx = this.$store.state.session.user.pbx
        myQuery.type = this.$store.state.session.user.type
        // 选择部门或技能组 但其下面无座席 故传显示无座席得值
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          myQuery.selectedAgentList = '000000'
        } else if (this.selectedAgentListClone.length !== 0) {
          myQuery.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        if (myQuery.reportType === 'call_report_agent') {
          myQuery.AgentID = ''
        }
        let data = {
          Method: 'exportAgent',
          Query: myQuery
        }
        // 导出详细excel更改method
        if (isDetailExpot === true) {
          data.Method = 'exportAgentReportDetail'
        }
        if (data.TimeType === 'other_half_hour') {
          delete data.yearReport
          delete data.monthReport
          delete data.dayReport
        }
        this.$store.dispatch('exportCallAgentReport', data).then(() => {
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.callReportAgent') + searchTime(this.query), id: this.id})
      }
    },
    components: {
      affix,
      unfold,
      // timePicker,
      dateTime,
      // reportTable,
      checkboxTable,
      headerOption,
      queryAgentTime,
      FormulaEditorDialog
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      // 获取通话技能组缓存
      this.$store.dispatch('getCache', {type: 'queues'}).then((peer) => {
        this.queues = peer
      })
      // 获取部门缓存
      this.$store.dispatch('getCache', {type: 'depts'}).then((dept) => {
        this.depts = dept.filter(item => {
          return item.pId
        })
        this.depts.push({
          name: '未分配部门',
          treePath: 'noDept'
        })
      })
      // 获取座席缓存
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agents = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        // this.ArrayList = deepClone(agents)
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .agent
    .agent_table
      .el-select
        margin-right 0px
        width 120px
    .agent_search
      .wrap_conti
        margin 14px 0 0 20px
        .ski
          margin-right 26px
        .chan_ag
          float left
          margin-right 20px
        .el-radio
          margin-right 30px
        .dept
          .el-radio
            margin-right 42px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 15px
      border-radius 50%
      margin 0px 0 0 6px
      .iconfont
        border none
        font-size 10px
        color $c-main
    .el-checkbox-group
      margin 20px 0 0 20px
      .serviceDisplayWrap
        display inline-block
        width 140px
    .el-select
      display inline-block
      margin-right 16px
      width 400px
      .sear
        margin-left 0
        margin-top 16px
      .ski
        margin-right 26px
      .ski2
        margin-right 10px
    .el-col-1
      height 36px
      line-height 36px
    .tab
      padding-bottom 20px
      .formal
        margin-left 10px
      .el-table .cell
      .el-table th>div
        padding 18px 4px
        .tex
        .te
          cursor pointer
        .set
          margin-right 10px
          position relative
          top 2px
          .icon-tixingweizhi
            font-size 10px
</style>
